﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Niaofei.Application.Services
{
    public class CaptchaValidator
    {
        private readonly Dictionary<string, DateTime> _activeCaptchas = new();
        private readonly TimeSpan _expirationTime = TimeSpan.FromMinutes(5);

        public void StoreCaptcha(string captcha)
        {
            // 清理过期验证码
            var expiredKeys = _activeCaptchas
                .Where(kvp => kvp.Value < DateTime.UtcNow)
                .Select(kvp => kvp.Key)
                .ToList();

            foreach (var key in expiredKeys)
            {
                _activeCaptchas.Remove(key);
            }

            // 添加新验证码
            _activeCaptchas[captcha] = DateTime.UtcNow.Add(_expirationTime);
        }

        public bool ValidateCaptcha(string userInput, string sessionCode)
        {
            if (string.IsNullOrWhiteSpace(userInput) || string.IsNullOrWhiteSpace(sessionCode))
            {
                return false;
            }

            // 查找匹配的验证码（不区分大小写）
            var key = _activeCaptchas.Keys
                .FirstOrDefault(k =>
                    k.Equals(sessionCode, StringComparison.OrdinalIgnoreCase) &&
                    _activeCaptchas[k] > DateTime.UtcNow);

            if (key == null)
            {
                return false;
            }

            // 移除已使用的验证码
            _activeCaptchas.Remove(key);

            // 比较用户输入（忽略大小写和空格）
            return key.Equals(userInput.Trim(), StringComparison.OrdinalIgnoreCase);
        }
    }
}